/**
 * Created by duguying on 2015/9/6.
 */
$(jQuery.fn.extend({
    draggable: function (pannel) {
        var mousedown_option = false;
        var mouseup_option = false;
        var origin_client_x = 0;
        var origin_client_y = 0;
        var box_x = 0;
        var box_y = 0;
        var _this = this;

        if(typeof pannel == "undefined"){
            pannel = this;
        }

        $(pannel).on("mousedown", function (e) {
            mousedown_option = true;
            mouseup_option = false;
            origin_client_x = e.clientX;
            origin_client_y = e.clientY;
            box_x = $(_this).offset().left;
            box_y = $(_this).offset().top;

            // parent margin fix
            var parent = $(_this).parent();
            box_x = box_x - $(parent).offset().left;
            box_y = box_y - $(parent).offset().top;

            // parent padding fix
            box_x = box_x - parseFloat($(parent).css("padding-left"));
            box_y = box_y - parseFloat($(parent).css("padding-top"));

            // self margin fix
            box_x = box_x - parseFloat($(_this).css("margin-left"));
            box_y = box_y - parseFloat($(_this).css("margin-top"));
        });

        $(document).on("mousemove", function (e) {
            if(mousedown_option){
                var x = e.clientX - origin_client_x;
                var y = e.clientY - origin_client_y;
                // move
                $(_this).css({"position": "relative","left": (box_x + x) + "px", "top": (box_y + y) + "px"});
            }
        }).on("mouseup", function (e) {
            mouseup_option = true;
            mousedown_option = false;
        });

        return this;
    }
}));